package personnal.blog2pdf.listener;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.annotation.BeforeStep;
import org.springframework.batch.core.listener.SkipListenerSupport;
import org.springframework.batch.item.ItemWriter;

import personnal.blog2pdf.data.PostError;
import personnal.blog2pdf.data.PostInfo;

public class PostInfoSkipListener extends SkipListenerSupport<PostInfo, PostInfo> {

    private static final Logger logger = Logger.getLogger(PostInfoSkipListener.class);

    private ItemWriter<PostError> postErrorWriter;

    private StepExecution stepExecution;

    @BeforeStep
    public void beforeStep(StepExecution stepExecution) {
        this.stepExecution = stepExecution;
    }

    @Override
    public void onSkipInProcess(PostInfo postInfo, Throwable t) {
        logger.warn("Item skipped (process): id=" + postInfo.getId());
        List<PostError> items = new ArrayList<PostError>();
        items.add(new PostError(postInfo.getId(), t));
        writePostError(items);
    }

    @Override
    public void onSkipInWrite(PostInfo postInfo, Throwable t) {
        logger.warn("Item skipped (write): id=" + postInfo.getId());
        List<PostError> items = new ArrayList<PostError>();
        items.add(new PostError(postInfo.getId(), t));
        writePostError(items);
    }

    private void writePostError(List<PostError> items) {
        try {
            this.postErrorWriter.write(items);
        } catch (Exception e) {
            logger.fatal("Can't write rejected items to the file", e);
            this.stepExecution.setTerminateOnly();
            // stepExecution.upgradeStatus(BatchStatus.STOPPED);
            // this.stepExecution.setExitStatus(ExitStatus.STOPPED);
        }
    }

    public void setPostErrorWriter(ItemWriter<PostError> postErrorWriter) {
        this.postErrorWriter = postErrorWriter;
    }
}
